import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

// 隐私政策文本
class PrivacyPolicyText extends StatelessWidget {
  final String normalText;
  // 替换标识
  final String replaceFlag;
  final String? highlightText;
  final String? privacyPolicyText;
  final String? userAgreementText;
  final TextStyle? normalStyle;
  final TextStyle? highlightStyle;
  final TextStyle? linkStyle;
  final VoidCallback? onPrivacyPolicyTap;
  final VoidCallback? onUserAgreementTap;

  const PrivacyPolicyText({
    Key? key,
    required this.normalText,
    required this.replaceFlag,
    this.highlightText,
    this.privacyPolicyText,
    this.userAgreementText,
    this.normalStyle,
    this.highlightStyle,
    this.linkStyle,
    this.onPrivacyPolicyTap,
    this.onUserAgreementTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final defaultNormalStyle =
        normalStyle ?? theme.textTheme.bodyMedium ?? const TextStyle();
    final defaultHighlightStyle = highlightStyle ??
        defaultNormalStyle.copyWith(
          color: theme.colorScheme.primary,
          fontWeight: FontWeight.bold,
        );
    final defaultLinkStyle = linkStyle ??
        defaultNormalStyle.copyWith(
          color: theme.colorScheme.primary,
          decoration: TextDecoration.underline,
        );

    // 分割文本以插入高亮部分和链接
    final textSpans = <TextSpan>[];
    final parts = normalText.split(replaceFlag);

    bool hasLightText = highlightText != null;
    for (int i = 0; i < parts.length; i++) {
      textSpans.add(TextSpan(text: parts[i], style: defaultNormalStyle));

      // 插入高亮文本
      if (i == 0 && hasLightText) {
        textSpans.add(
          TextSpan(
            text: highlightText,
            style: defaultHighlightStyle,
          ),
        );
      }

      // 插入用户协议链接
      if (i == (hasLightText ? 1 : 0) && userAgreementText != null) {
        textSpans.add(
          TextSpan(
            text: userAgreementText,
            style: defaultLinkStyle,
            recognizer: TapGestureRecognizer()
              ..onTap = () async {
                if (onUserAgreementTap != null) {
                  onUserAgreementTap!();
                }
              },
          ),
        );
      }

      // 插入隐私政策链接
      if (i == (hasLightText ? 2 : 1) && privacyPolicyText != null) {
        textSpans.add(
          TextSpan(
            text: privacyPolicyText,
            style: defaultLinkStyle,
            recognizer: TapGestureRecognizer()
              ..onTap = () async {
                if (onPrivacyPolicyTap != null) {
                  onPrivacyPolicyTap!();
                }
              },
          ),
        );
      }
    }

    return RichText(
      text: TextSpan(
        children: textSpans,
        style: const TextStyle(
          wordSpacing: 0,
          letterSpacing: 0,
        ),
      ),
      textAlign: TextAlign.center,
    );
  }
}
